package com.lhy.realm;

import com.lhy.entity.Permission;
import com.lhy.entity.User;
import com.lhy.service.PermissionService;
import com.lhy.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author：罗昊宇
 * @Package：com.lhy.realm
 * @Project：shiro-framwork
 * @name：MyRealm
 * @Date：2024/5/9 0009  16:58
 * @Filename：MyRealm
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
     private PermissionService permissionService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //principals表示当前登录者的信息
        User user = (User) principals.getPrimaryPrincipal();
        //根据id查询该用户具有的权限
        List<Permission> permissionList = permissionService.selectByUserId(user.getUserid());
        if (permissionList.size()>0){
            //SimpleAuthorizationInfo用于存储用户的授权信息。
            SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
            //map将每个Permission对象转换为其percode属性的值  collect将映射后的结果收集到一个新的列表中，并返回该列表
            List<String> list = permissionList.stream().map(item -> item.getPercode()).collect(Collectors.toList());
            //将权限字符串列表添加到SimpleAuthorizationInfo对象中，表示该用户具有这些权限。
            info.addStringPermissions(list);
            return info;
        }

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取账号
        String username = (String) token.getPrincipal();
        //调用service中根据username查询用户信息
      User user=  userService.selectByUsername(username);
        if (user!=null){
            ByteSource bytes = ByteSource.Util.bytes(user.getSalt());
            //shiro会帮我们进行密码的比对，因为你的realm指定了加密器--shiro在比密码时，先对你都密码进行加密，加密后和数据库的密码比对
            //内部进行比对
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getUserpwd(),bytes,this.getName());
            return info;
        }

        return null;
    }
}
